﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.WeixinMP.Impls;
using Microhard.WeixinMP.Interfaces;
using Microhard.WeixinMP.Unities;
using Microhard.WeixinMP.Models;
using System.Configuration;
using Micrhard.FMCG.Server.Interface;
using Microhard.Core;
using Micrhard.FMCG.Server.Msg;

namespace Micrhard.FMCG.Server.Weixin
{
    public class OnFoucsWXMP : BaseResponseImpl
    {
        public override Microhard.WeixinMP.Interfaces.WeixinCommand Command
        {
            get
            {
                WeixinCommand wc = new WeixinCommand();
                wc.Event = "CLICK";
                wc.EventKey = "onFoucs";
                return wc;
            }
        }

        protected override Microhard.WeixinMP.Models.WeixinBaseData<object> CreateFeatureResponse(Microhard.WeixinMP.Models.RequestServiceModel request, Microhard.WeixinMP.Models.WeixinBaseData<object> response)
        {
            //创建token
            string token = SessionSecurity.CreateToken(response.ToUserName);
            //创建会话成功，发起服务
            response.MsgType = WeixinMsgType.Text;
            response.FuncFlag = WeixinMsgType.FuncFlag_False;
            WeixinTxt result = new WeixinTxt();
            string onFoucsMPUrl = ConfigurationManager.AppSettings["OnFoucsMP"];
            string finUrl = string.Format(this.UrlFormat, onFoucsMPUrl, token, response.EncodeWeixinToUserName, string.Empty, request.ConversationID, request.WXMPAccountUser.CompanyID);
            Log.Info("OnFoucsWXMP", finUrl);
            //生成onauth2.0地址
            string onauthurl = ConfigurationManager.AppSettings["OnAuth20"];
            string oaparms = "?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            onauthurl = onauthurl + string.Format(oaparms, request.WXMPAccountUser.AppID, System.Web.HttpUtility.UrlEncode(finUrl));

            ICustomer cus = IoC.Resolve<ICustomer>();
            if (cus.IsExist(new Models.CustomerModel
            {
                OpenID = response.ToUserName
            }))
            {
                result.Content = BindingAccountMsg.HasFoucs;
            }
            else
            {
                //生成链接地址    
                result.Content = string.Format(BindingAccountMsg.OnFoucsLink, onauthurl);
            }

            response.Content = result;
            return response;
        }
    }
}
